from django.shortcuts import redirect, reverse, HttpResponse
from django.utils.deprecation import MiddlewareMixin
# 引入setting 文件
from django.conf import settings


class Auth_Md(MiddlewareMixin):

    def process_request(self, request):
        # 获取当前的url
        url_path = request.path_info
        # 判断是否在白名单中
        for item in settings.UNAUTH_WHITE_URL:
            if url_path == item:
                return None

        # 从Session中获取user
        obj_user = request.session.get('user')
        # 判断是否存在
        if obj_user:
            request.user = obj_user
        else:
            return redirect(reverse('login'))

        # ===== 获取当前的URL并且判断 是否再当前用户的权限列表中！=====
        # 从session中获取当前用户的权限
        permission_list = request.session.get('permission_list')

        # 遍历permission_list, 判断当前请求的URL是否在permission_List中
        for item in permission_list:
            # 如果当前请求的URL在permission_list中
            if item == url_path:
                return None
            # 判断url是否以item / url_path开始？
            if url_path.startswith(item):
                return None
        return HttpResponse("您无权访问改页面！")



